package com.lingdong.onlinejudge.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingdong.onlinejudge.common.ErrorCode;
import com.lingdong.onlinejudge.common.PageRequest;
import com.lingdong.onlinejudge.exception.BusinessException;
import com.lingdong.onlinejudge.model.dto.user.UserExpDto;
import com.lingdong.onlinejudge.model.dto.user.UserListDto;
import com.lingdong.onlinejudge.model.dto.user.UserPageListDto;
import com.lingdong.onlinejudge.model.entity.User;
import com.lingdong.onlinejudge.model.vo.user.UserUpdateDto;
import com.lingdong.onlinejudge.model.vo.user.UserVo;
import com.lingdong.onlinejudge.service.UserService;
import com.lingdong.onlinejudge.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author lzw
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{

    @Resource
    private UserMapper userMapper;

    /**
     * 更新用户信息
     * @param userUpdateDto 用户信息
     * @return 结果
     */
    @Override
    public Boolean updateUser(UserUpdateDto userUpdateDto) {
        Long id = userUpdateDto.getId();
        if (id == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User user = baseMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        String userName = userUpdateDto.getUserName();
        String userProfile = userUpdateDto.getUserProfile();
        if (StringUtils.isAnyBlank(userName, userProfile)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userName.length() > 20 || userProfile.length() > 50){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"用户名与简介超出长度限制");
        }
        BeanUtils.copyProperties(userUpdateDto, user);
        int i = userMapper.updateById(user);
        if (i <= 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    /**
     * 根据id查询用户信息
     * @param id 用户id
     * @return 结果
     */
    @Override
    public UserVo queryUser(Long id) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    /**
     * 分页查询用户信息
     * @param pageListDto 分页参数
     * @return 结果
     */
    @Override
    public Page<UserVo> queryUserByPage(UserPageListDto pageListDto) {
        String userAccount = pageListDto.getUserAccount();
        String userName = pageListDto.getUserName();
        String email = pageListDto.getEmail();
        PageRequest page = pageListDto.getPage();
        // 构造查询参数
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like(StringUtils.isNotBlank(userAccount), "user_account", userAccount);
        userQueryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        userQueryWrapper.like(StringUtils.isNotBlank(email), "email", email);
        Page<User> userPage = userMapper.selectPage(
                new Page<>(page.getCurrent(), page.getPageSize()), userQueryWrapper);
        // 转换
        Page<UserVo> userVoPage = new Page<>();
        BeanUtils.copyProperties(userPage, userVoPage);
        userVoPage.setRecords(userPage.getRecords().stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }).collect(Collectors.toList()));
        return userVoPage;
    }

    /**
     * 删除用户
     * @param idList 用户id列表
     * @return 结果
     */
    @Override
    @Transactional
    public Boolean deleteUser(List<Long> idList) {
        if (idList == null || idList.size() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int i = userMapper.deleteBatchIds(idList);
        if (i <= 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }

    /**
     * 查询用户列表
     * @param userListDto 用户列表参数
     * @return 结果
     */
    @Override
    public List<UserVo> queryUserList(UserListDto userListDto) {
        String userName = userListDto.getUserName();
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.like(StringUtils.isNotBlank(userName), "user_name", userName);
        return userMapper.selectList(userQueryWrapper).stream().map(user -> {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user, userVo);
            return userVo;
        }).collect(Collectors.toList());
    }

    /**
     * 用户经验
     * @param userExpDto 用户经验
     * @return 结果
     */
    @Override
    public Boolean userExp(UserExpDto userExpDto) {
        Long userExp = userExpDto.getUserExp();
        Long userId = userExpDto.getId();
        if (userExp == null || userId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (userExp <= -20 || userExp >= 20){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "经验超出范围");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", userId);
        User user = baseMapper.selectOne(queryWrapper);
        if (user == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Long exp = user.getUserExp();
        user.setUserExp(exp + userExp < 0 ? 0 : exp + userExp);
        int i = userMapper.updateById(user);
        if (i <= 0){
            throw new BusinessException(ErrorCode.OPERATION_ERROR);
        }
        return true;
    }
}




